package com.lmj.common;

import com.lmj.dto.DataResponse;
import com.lmj.pojo.User;
import com.lmj.utils.RedisUtil;
import com.lmj.utils.TokenUtil;
import net.minidev.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /**
         * 从请求头中取出token，并判断其是否存在和合法
         */
//        String token = request.getHeader("token");
//
//        if (StringUtils.isEmpty(token) || !tokenUtil.verifyToken(token)) {
//            response.getWriter().write(this.errorResponse("未登录"));
//            return false;
//        } else {
//            return true;
//        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        ThreadUtils.remove();
    }

    // 私有方法，返回json字符串格式的错误信息
    private String errorResponse(String msg) {
        Map map = new HashMap(3) {
            {
                put("code", -1);
                put("msg", msg);
            }
        };
        return JSONObject.toJSONString(map);
    }

}
